package com.ac.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ac.model.AuthApi;
import com.ac.model.AuthRole;
import com.ac.model.AuthUser;
import com.ac.util.TreeUtil;

import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class AuthApiService {

	private final AuthRoleService RoleService;

	final MongoTemplate mongo;

	public List<AuthApi> list() {
		return mongo.findAll(AuthApi.class);
	}

	@Transactional(rollbackFor = Exception.class)
	public void insert(AuthApi api) {
		api.insert();
		mongo.insert(api);
	}

	@Transactional(rollbackFor = Exception.class)
	public void update(AuthApi api) {
		api.update();
		Criteria criteria = Criteria.where("_id").is(api.getId());
		Query query = Query.query(criteria);
		Update update = new Update();
		update.set("parentId", api.getParentId());
		update.set("title", api.getTitle());
		update.set("url", api.getUrl());
		update.set("sort", api.getSort());
		update.set("type", api.getType());
		update.set("updateTime", api.getUpdateTime());
		mongo.updateFirst(query, update, AuthApi.class);
	}

	@Transactional(rollbackFor = Exception.class)
	public void remove(AuthApi api) {

		// 移除自己
		mongo.remove(api);

		// 移除所有子节点
		List<String> removeList = TreeUtil.removeId(api, AuthApi.class);
		removeList.add(api.getId());

		// 移除角色管理api列表
		Update update = new Update().pullAll("apiList", removeList.toArray(new String[removeList.size()]));
		mongo.updateMulti(Query.query(Criteria.where("id").exists(true)), update, AuthRole.class);
	}

	public List<AuthApi> apiList(AuthUser authUser) {
		List<AuthRole> roleList = RoleService.roleList(authUser, new Document("status", true));
		Set<String> apiIdList = new HashSet<String>();
		for (AuthRole authRole : roleList) {
			for (String menuId : authRole.getApiList()) {
				apiIdList.add(menuId);
			}
		}

		Criteria criteria = Criteria.where("_id").in(apiIdList);
		Query query = Query.query(criteria);

		List<AuthApi> list = mongo.find(query, AuthApi.class);
		return list;
	}

}
